<?php 


class Login{
	
	
	public static $msgs = array();
	
	function __construct()
	{
		
	}

	/*
		Function will login user and set appropriate session variable 
	*/
	
	function do_login($data)
	{
		global $db, $msgError;
		$username = $db->escape($data['username']);
		$password = md5($data['password']);
		$db->query(" SELECT * FROM admin_users WHERE username = '{$username}' AND password = '{$password}' and active = 1 ");
		$result = $db->fetch();
		
		if(count($result) > 0)
		{
			if( $result['username'] == $username && $result['password'] == $password )
			{
				$_SESSION['admin_id'] = $result['id'];
				$_SESSION['group_id'] = $result['group_id'];
				$_SESSION['is_admin'] = $result['user_type'];
				redirect("admin/home.php");		
			}
		}
		else
		{
			$msg = 'Error! Please enter valid username and password.';
			$msgError .= '<p>'.$msg.'</p>';
		}
	}
	
	/*
		Functoin redirect to home if user is login and try access login/forget password/reset password pages
	*/
	
	function redirectLoginUser()
	{
		if( (isset($_SESSION['admin_id']) && $_SESSION['admin_id'] != '' ) )
		{
			redirect("admin/home.php");
		}	
	}
	
	/*
		Functoin will validate email, if valid email and email exist then send password reset email
	*/
	
	function sendPasswordResetEmail($email)
	{
		global $db, $msgError;
		$email = trim($email);
		
		if($email == ''){
			$this->msgs[] = 'Please enter email address.';
		}
		elseif(!isValidEmail($email))
		{
			 $this->msgs[] = 'Email address is invalid.';
		}
		else
		{
			$email = $db->escape($email);
			$user = $db->first(" SELECT * FROM admin_users WHERE email = '{$email}' ");
			if( ! isset($user['id']) ) 
			{
				$this->msgs[] = 'Email address does not exist.';
			}
		}
		if( empty($this->msgs) )
		{
			$password_reset_code = md5(time());
			$record =  array("password_reset_code" => $password_reset_code);
			$where = array( "id" => $user['id']);
			$db->update("admin_users", $record, $where);
			$user['password_reset_code'] = $password_reset_code;
			if( $this->sendResetPasswordEmail($user) )
			{
				redirect("admin/index.php?send=1");		
			}
			else
			{
				$this->msgs[] = 'Some error occurs. Password reset email can not be send.';
			}
			
			
		}
		
		$msgError = '';
		foreach($this->msgs as $msg)
		{
			$msgError .= '<p>'.$msg.'</p>';
		}
		
	}
	
	/*    
		function will send an password reset email, link to reset password is send through email template.
	*/
	function sendResetPasswordEmail($user)
	{
		global $db, $config;
		$email_template_data = $this->getEmailTemplate();
		
		$link = $config['baseurl']."/admin/reset_password.php?reset_code=".$user['password_reset_code'];
		$link = '<a href="'.$link.'"> '.$link.'  </a>';
		$site_name = '<a href="'.$config['baseurl'].'"> '.$config['sitename'].'  </a>';
		$array1 = array('{USERNAME}', '{LINK}', '{SITE_NAME}', '{SITE_URL}');
		$array2 = array($user['username'], $link, $site_name, $config['siteurl']);
		$email_message =  str_replace($array1, $array2, $email_template_data['template_body']);
		$subject = $email_template_data['template_subject'];
		return sendEmail($user['email'], $subject, $email_message);
	}
	
	/*
		return the first email template of type forget password
	*/
	
	function getEmailTemplate()
	{
		global $db;
		return $db->first("SELECT * FROM email_templates WHERE email_template_type_id = 3 order by template_name");
	}
	
	/*
		Function will check weather the provide password reset code is correct ( exist in DB )
	*/
	
	
	function isValidCode($password_reset_code)
	{
		global $db;
		$password_reset_code = trim($password_reset_code);
		if($password_reset_code != '')
		{
			$user = $db->first(" SELECT * FROM admin_users WHERE password_reset_code = '".$db->escape($password_reset_code)."' ");
			if( isset($user['id']) ) 
			{
				return TRUE;
			}	
		}
		
		return FALSE;
	}
	
	/*
		Function will update password agaist the password reset code, after validation
	*/
	
	function resetPassword($data)
	{
		global $db, $config, $msgError;
		
		if( $data['password'] == '' OR $data['confirm_password'] == '' )
		{
			$this->msgs[] = 'Please enter password.';
		}
		
		if($data['password'] != $data['confirm_password'])
		{
			$this->msgs[] = 'Password and confirm password do not match.';
		}
		
		$password_reset_code = $data['reset_code'];
		$password = md5($data['password']);
		if( empty($this->msgs) )
		{
			$record =  array("password" => $password, 'password_reset_code'=>'');
			$where = array( "password_reset_code" => $password_reset_code);
			
			if( $db->update("admin_users", $record, $where) )
			{
				redirect("admin/reset_password.php?action=reset_password&updated=1");		
			}
		}
		
		$msgError = '';
		foreach($this->msgs as $msg)
		{
			$msgError .= '<p>'.$msg.'</p>';
		}
	}
	
}

?>